<script setup lang="ts">
import ImageCompressor from "image-compressor.js"
import type {Ref} from "vue-demi";
import {Notification} from "@arco-design/web-vue";
import { ref } from 'vue'

const defEmit = defineEmits(["imgs", "delImg"])

const defProps = defineProps({
  width: {
    type: String,
    default: "200px"
  },
  height: {
    type: String,
    default: "100px"
  },
  src: {
    type: Array<img>,
    default: []
  }
})

export interface img {
  ossId?: string
  id?: string
  file?: File
  src: string
  fileName?: string
  isLocal?: Boolean
  /**
   * 是否为刚才选择
   */
  isNow?: Boolean
  clientUrl?: string,
  abs_id?: string
}


const images:Ref<img[]> = ref([])

/**
 * 选择
 */
const selectImg =  () => {
  images.value = defProps.src
  const input = document.createElement("input")

  input.type = "file"
  input.accept = "image/gif,image/jpeg,image/jpg,image/png"
  input.multiple = true

  input.onchange = async (e) => {
    if (e.target == null) {
      return;
    }
    //@ts-ignore
    const files = e.target.files
    for (let i = 0; i < files.length;i++) {
      await new Promise(resolve => {
        let img = new ImageCompressor()
        img.compress(files[i], {
          quality: 0.6
        }).then(res => {
          let readed = new FileReader()
          readed.readAsDataURL(res)

          readed.onload = function (a) {
            if (a.target == null) {
              return
            }
            images.value.push({
              id: new Date().toString(),
              file: res as File,
              src: a.target.result as string,
              //@ts-ignore
              fileName: res.name,
              isNow: true
            })
            resolve(res)
          }

        })

      })
    }
    defEmit("imgs", images)
  }
  input.click()

}

/**
 * 删除
 */
const delImg = (i:img) => {
  if (defProps.src.length <= 1) {
    Notification.error({
      title: "无法修改",
      content: "必须保留一张图片",
      duration: 2000
    })
    return;
  }

  // 创建一个新数组，避免直接修改props
  const newImages = [...defProps.src];
  
  // 找到要删除的图片的索引
  const index = newImages.findIndex(img => 
    (img.ossId && img.ossId === i.ossId) || 
    (img.id && img.id === i.id)
  );

  if (index !== -1) {
    newImages.splice(index, 1);
    defEmit("delImg", ref(newImages));
  }
}

const hien = ref(false)

</script>

<template>
  <div class="img-upload-container">
    <a-image width="200px" height="100px" v-if="src.length == 0" @click="selectImg" />

    <a-carousel class="imgs" :style="`width:${width};height:${height}`" v-if="src.length != 0" >
      <a-carousel-item v-for="(i, index) in src" :key="index">
        <a-image :width="width" :height="height" :src="i.clientUrl ? i.clientUrl : i.src"  />
      </a-carousel-item>
    </a-carousel>

  <a-button type="text" @click="selectImg">新增</a-button>
  <a-button type="text" @click="hien = !hien">全部图片</a-button>

  <a-modal title="图片" v-model:visible="hien" >
      <div class="group">
        <div class="img" v-for="(i, index) in src" :key="index">
          <a-image :width="width" :height="height" :src="i.clientUrl ? i.clientUrl : i.src" />
          <a-button type="text" status="danger" @click="delImg(i)">删除</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.group {
  .img {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-right: 10px;
  }
  display: flex;
}

</style>